package com.itheima.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.User;
import com.itheima.pojo.UserTotal;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.io.IOException;

@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserService userService;


	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        Page<User> UserPage = new Page<>(currentPage, pageSize);
        Page<User> page = userService.page(UserPage);
        System.out.println(page.getRecords().toString());
        UserTotal userTotal = new UserTotal(page.getRecords(),page.getTotal());
        return new Result(Code.GET_OK,userTotal);
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {
        boolean save = userService.save(user);
        if(!save){
            return new Result(Code.SAVE_ERR);
        }
        return new Result(Code.SAVE_OK);
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean b = userService.removeById(id);
        if(!b){
            return new Result(Code.DELETE_ERR);
        }
        return new Result(Code.DELETE_OK);
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean b = userService.updateById(user);
        if(!b){
            return new Result(Code.UPDATE_ERR);
        }
        return new Result(Code.UPDATE_OK);
    }

}
